package com.danjinwulian.quartz.task;

//import com.danjinwulian.iot.service.TencentIotService;
import com.danjinwulian.common.constant.CacheConstants;
        import com.danjinwulian.common.core.domain.entity.IotDevice;
import com.danjinwulian.common.core.domain.entity.IotProduct;
import com.danjinwulian.common.core.redis.RedisCache;
import com.danjinwulian.common.utils.DateUtils;
import com.danjinwulian.common.utils.WxUtils;
import com.danjinwulian.device.service.IIotDeviceService;
import com.danjinwulian.device.service.IIotProductService;
import com.danjinwulian.device.service.IMpWeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
        import org.springframework.stereotype.Component;
import com.danjinwulian.common.utils.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask
{
    @Autowired
    private IIotProductService productService;
    @Autowired
    private IIotDeviceService deviceService;

    @Autowired
    private IMpWeixinService weixinService;
//    @Autowired
//    private TencentIotService tencentIotService;

    private static RedisCache redisCache;

    @Value("${weixin.danjinwulian.appid}")
    private String danjinIotAppId;
    @Value("${weixin.danjinwulian.secret}")
    private String danjinIotSecret;
    @Value("${weixin.message.deviceExceptionTemplateId}")
    private String deviceExceptionTemplateId;
    @Value("${weixin.message.deviceExceptionTousers}")
    private String[] deviceExceptionTousers;

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
    {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params)
    {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams()
    {
        System.out.println("执行无参方法");
    }

    /**
     * 检查设备运行状态
     */
    public void checkDeviceStatus()
    {
//        System.out.println("执行检查设备运行状态方法");
        //查找所有产品
        List<IotProduct> products = productService.selectProductList(new IotProduct());
//        for (IotProduct product : products) {
//            IClientProfile profile = DefaultProfile.getProfile(product.getRegionId(), accessKey, accessSecret);
//            DefaultAcsClient client = new DefaultAcsClient(profile);
//
//            //设备的名称
//            List<String> deviceNames = new ArrayList<String>();
//            IotDevice iotDevice = new IotDevice();
//            iotDevice.setProductId(product.getProductId());
//            //查找产品下的所有设备
//            List<IotDevice> devices = deviceService.selectDeviceList(iotDevice);
//            for (IotDevice device : devices) {
//                deviceNames.add(device.getDeviceName());
//            }
//
//            int listCount = deviceNames.size();
//            if (listCount > 0) {
//                //该接口用于查看一个产品下多个设备的运行状态，单次最多可查询50个设备
//                int batchSize = 50, batchCount = 1;
//                if ((listCount % batchSize) > 0) {
//                    batchCount = (int) Math.floor(listCount / batchSize) + 1;
//                } else {
//                    batchCount = (int) Math.floor(listCount / batchSize);
//                }
//                for (int i = 1; i <= batchCount; i++) {
//                    int fromIndex = (i - 1) * batchSize;
//                    int toIndex = i * batchSize;
//                    if (toIndex > listCount) {
//                        toIndex = listCount;
//                    }
//
//                    //批量获取设备运行状态的设备名称
//                    List<String> batchDeviceNames = new ArrayList<String>();
//                    for (int j = fromIndex; j < toIndex; j++) {
//                        batchDeviceNames.add(deviceNames.get(j));
//                    }
//
//                    if (!batchDeviceNames.isEmpty()) {
//                        BatchGetDeviceStateResponse response = null;
//                        BatchGetDeviceStateRequest request = new BatchGetDeviceStateRequest();
//                        request.setIotInstanceId(product.getInstanceId());
//                        request.setDeviceNames(batchDeviceNames);
//                        request.setProductKey(product.getProductKey());
//
//                        try {
//                            response = client.getAcsResponse(request);
//
//                            if (response.getSuccess() != null && response.getSuccess()) {
//                                List<BatchGetDeviceStateResponse.DeviceStatus> dataList = response.getDeviceStatusList();
//                                for (BatchGetDeviceStateResponse.DeviceStatus deviceStatus : dataList) {
//                                    List<IotDevice> deviceList = devices.stream().filter(r -> r.getDeviceName().equals(deviceStatus.getDeviceName())).collect(Collectors.toList());
//                                    if (StringUtils.isNotEmpty(deviceList)) {
//                                        iotDevice = deviceList.get(0);
//                                    }
//                                    if ("UNACTIVE".equals(deviceStatus.getStatus()) && !IoTConstants.DEVICE_UNACTIVE.equals(iotDevice.getStatus())) {
//                                        iotDevice.setStatus(IoTConstants.DEVICE_UNACTIVE);
//                                        deviceService.updateDeviceStatus(iotDevice);
//                                    }
//                                    else if ("ONLINE".equals(deviceStatus.getStatus()) && !IoTConstants.DEVICE_ONLINE.equals(iotDevice.getStatus())) {
//                                        iotDevice.setLastOnlineTime(DateUtils.getNowDate());
//                                        iotDevice.setStatus(IoTConstants.DEVICE_ONLINE);
//                                        deviceService.updateDeviceStatus(iotDevice);
//                                    }
//                                    else if ("OFFLINE".equals(deviceStatus.getStatus()) && !IoTConstants.DEVICE_OFFLINE.equals(iotDevice.getStatus())) {
//                                        iotDevice.setLastOfflineTime(DateUtils.getNowDate());
//                                        iotDevice.setStatus(IoTConstants.DEVICE_OFFLINE);
//                                        deviceService.updateDeviceStatus(iotDevice);
//                                    }
//                                    else if ("DISABLE".equals(deviceStatus.getStatus()) && !IoTConstants.DEVICE_DISABLE.equals(iotDevice.getStatus())) {
//                                        iotDevice.setStatus(IoTConstants.DEVICE_DISABLE);
//                                        deviceService.updateDeviceStatus(iotDevice);
//                                    }
//                                }
//                            } else {
//                                System.out.println("批量设备状态查询失败: "+JSON.toJSONString(response));
//                            }
//                        } catch (ClientException e) {
//                            e.printStackTrace();
//                            System.out.println("批量设备状态查询失败: "+JSON.toJSONString(response));
//                        }
//                    }
//                }
//            }
//        }
    }

    /**
     * 检查设备下线异常（设备下线超过30分钟未上线）
     */
    public void checkDevicesOfflineException()
    {
        // 获取accessToken
//        String accessToken = weixinService.getAccessToken("danjinwulian", danjinIotAppId, danjinIotSecret);
        String accessToken = "";
        if (StringUtils.isNotEmpty(accessToken)) {
            List<IotDevice> list = deviceService.selectOfflineExceptionDeviceList();
            System.out.println("设备下线超过30分钟未上线的设备数为: "+list.size());
            for (IotDevice device : list) {
                String deviceKey = CacheConstants.IOT_DEVICE_KEY + "offlineException_" + device.getDeviceName();
                if(StringUtils.isNull(redisCache.getCacheObject(deviceKey))) {
                    for (String touser : deviceExceptionTousers) {
                        Map<String, Object> params = new HashMap<>();
                        params.put("touser", touser);
                        params.put("template_id", deviceExceptionTemplateId);

                        Map paramsData = new HashMap();
                        paramsData.put("thing6", WxUtils.createParamsData(device.getHotelName()+"【"+device.getRoomName()+"】", null));
                        paramsData.put("thing12", WxUtils.createParamsData("设备下线超过30分钟未上线", null));
                        paramsData.put("phrase13", WxUtils.createParamsData("设备下线", null));
                        paramsData.put("time15", WxUtils.createParamsData(DateUtils.getTime(), null));
                        params.put("data", paramsData);

                        weixinService.pushTemplateMessage(accessToken, params);
                    }
                    redisCache.setCacheObject(deviceKey, DateUtils.getTime(), 12, TimeUnit.HOURS);
                }
            }
        }
    }

    /**
     * 检查设备断电异常（设备通电超过20小时未断电）
     */
    public void checkDevicesPoweroffException()
    {
        // 获取accessToken
//        String accessToken = weixinService.getAccessToken("danjinwulian", danjinIotAppId, danjinIotSecret);
        String accessToken = "";
        if (StringUtils.isNotEmpty(accessToken)) {
            List<IotDevice> list = deviceService.selectPoweroffExceptionDeviceList();
            System.out.println("设备通电超过20小时未断电的设备数为: "+list.size());
            for (IotDevice device : list) {
                String deviceKey = CacheConstants.IOT_DEVICE_KEY + "poweroffException_" + device.getDeviceName();
                if(StringUtils.isNull(redisCache.getCacheObject(deviceKey))) {
                    for (String touser : deviceExceptionTousers) {
                        Map<String, Object> params = new HashMap<>();
                        params.put("touser", touser);
                        params.put("template_id", deviceExceptionTemplateId);

                        Map paramsData = new HashMap();
                        paramsData.put("thing6", WxUtils.createParamsData(device.getHotelName()+"【"+device.getRoomName()+"】", null));
                        paramsData.put("thing12", WxUtils.createParamsData("设备通电超过20小时未断电", null));
                        paramsData.put("phrase13", WxUtils.createParamsData("人走断电", null));
                        paramsData.put("time15", WxUtils.createParamsData(DateUtils.getTime(), null));
                        params.put("data", paramsData);

                        weixinService.pushTemplateMessage(accessToken, params);
                    }
                    redisCache.setCacheObject(deviceKey, DateUtils.getTime(), 12, TimeUnit.HOURS);
                }
            }
        }
    }
}
